package idiolect.helpers;

import idiolect.core.IOUtil;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;

public class MultitranTranslationHelper extends AbstractHelper {

    public MultitranTranslationHelper(String request, ResponseAcceptor requestor) {
        super(request, requestor, 0);
    }

    public void run() {
        try {
            URL pageURL = new URL("http://www.multitran.ru/c/m.exe?l1=1&l2=2&s=" + URLEncoder.encode(request));
            String page = new String(IOUtil.getContent(pageURL));
            int pos = page.indexOf("createAutoComplete();");
            if (pos == -1)
                return;
            pos = page.indexOf("</tr><tr>", pos);
            if (pos == -1)
                return;
            int pos2 = page.indexOf("</table>", pos);
            if (pos2 == -1)
                return;
            StringBuilder sb = new StringBuilder("<html><body><head><base href=\"").
                    append(pageURL).append("\"></head><table>");
            sb.append(page.substring(pos + 5, pos2)).append("</table></body></html>");
            response = sb.toString()
                    .replaceAll("<a\\shref=\"m.exe\\?a=\\d+(\\&)*UserName=[^\"]+\"><i>[^<]+<\\/i><\\/a>", "")
                    .replaceAll("\\(\\s+", "(")
                    .replaceAll("\\s+\\)", ")")
                    .replaceAll("\\(\\)", "")
                    .replaceAll("<a", "<span")
                    .replaceAll("</a", "</span");
        } catch (IOException e) {
            e.printStackTrace();
            response = null;
        }
    }
}
